package com.yue.modbus.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpClient {
    private static final org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(new MultiThreadedHttpConnectionManager());
    private String baseUrl;

    public HttpClient() {
    }
    public String post(String url, Map<String,Object> params, String body, int timeOutSeconds) {
        PostMethod method = new PostMethod(url);
        try {
            method.setRequestBody(body);
            if(params!=null){
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    method.addParameter(entry.getKey(), entry.getValue().toString());
                }
            }
            httpClient.getParams().setSoTimeout(timeOutSeconds * 1000);
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeOutSeconds * 1000);
            httpClient.executeMethod(method);
            byte[] responseBody = method.getResponseBodyAsString().getBytes(method.getResponseCharSet());
            // 在返回响应消息使用编码(utf-8或gb2312)
            return new String(responseBody, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("http post error", e);
            return null;
        } finally {
            method.releaseConnection();
        }
    }

    public String get(String url, int timeOutSeconds) {
        GetMethod method = new GetMethod(url);
        try {
            httpClient.getParams().setSoTimeout(timeOutSeconds * 1000);
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeOutSeconds * 1000);
            httpClient.executeMethod(method);

            // 返回响应消息
            byte[] responseBody = method.getResponseBodyAsString().getBytes(method.getResponseCharSet());
            // 在返回响应消息使用编码(utf-8或gb2312)
            return new String(responseBody, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("http get error", e);
            return null;
        } finally {
            method.releaseConnection();
        }

    }
}
